"use client";
import Search, { SearchProps } from "antd/es/input/Search";
import style from "./index.module.scss";
import {
  Badge,
  Button,
  Drawer,
  Dropdown,
  Modal,
  Popconfirm,
  Popover,
  Radio,
  Select,
  Space,
  Table,
  Tooltip,
  message,
} from "antd";
import { useEffect, useState } from "react";
import CourseForm from "./CourseForm";
import {
  addVideo,
  auditSubject,
  auditVideo,
  delCourse,
  delVideo,
  getCourse,
  getVideo,
  updateCourse,
  updateVideo,
} from "@/api";
import {
  COURSE_APPLY,
  COURSE_STATUS,
  SEVER_URL,
  getCourseContentObj,
  getCourseObj,
} from "@/configs/constant";
import { useForm } from "antd/es/form/Form";
import TextArea from "antd/es/input/TextArea";
import TableCom from "../TableCom";
import { DownOutlined } from "@ant-design/icons";
import CourseModal from "../CourseModal";
import { Span } from "next/dist/trace";
type TCourse = {
  videoStatus: number;
  videoName: string;
  videoLink: string;
  updateTime: string;
};
interface DataType {
  id: number;
  subjectName: string;
  subjectType: string;
  subjectHead: string;
  subjectIsApply: number;
  subjectStatus: number;
  children?: TCourse[];
}
type TStatus = "default" | "processing" | "success" | "error" | "warning";
interface CourseManageProps {
  getVideos: (
    pageNum: number,
    pageSize: number,
    videoName?: string,
    videoStatus?: number,
    videoType?: string
  ) => void;
  total: number;
  courses: DataType[];
}
export default function CourseManage(props: CourseManageProps) {
  const { getVideos, total, courses } = props;
  const COURSE_CLOUMNS = [
    {
      title: "课题封面",
      dataIndex: "subjectHead",
      key: "subjectHead",
      align: "center",
      width: "120px",

      render: (_: any, record: any) => {
        return (
          <>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={`${SEVER_URL}${record.subjectHead}`}
              width={60}
              height={60}
              alt=""
            />
          </>
        );
      },
    },
    {
      title: "课题名称",
      dataIndex: "subjectName",
      key: "subjectName",
      align: "center",
      width: "200px",
    },
    {
      title: "课程类型",
      dataIndex: "subjectType",
      key: "subjectType",
      align: "center",
      width: "120px",
    },

    {
      title: "状态",
      dataIndex: "subjectStatus",
      key: "subjectStatus",
      align: "center",
      width: "150px",
      render: (_: any, record: any) => {
        return (
          <>
            <Dropdown
              menu={{
                items: [
                  {
                    label: (
                      <Badge
                        status={getCourseContentObj(1)?.status as TStatus}
                        text={getCourseContentObj(1)?.text}
                      />
                    ),
                    key: 1,
                    onClick: () => handleChangeCourseStatus(1, record.id),
                  },
                  {
                    label: (
                      <Badge
                        status={getCourseContentObj(2)?.status as TStatus}
                        text={getCourseContentObj(2)?.text}
                      />
                    ),
                    key: 2,
                    onClick: () => handleChangeCourseStatus(2, record.id),
                  },
                ],
              }}
            >
              <Badge
                status={
                  getCourseContentObj(record.subjectStatus)?.status as TStatus
                }
                text={getCourseContentObj(record.subjectStatus)?.text}
              />
            </Dropdown>

            <Modal
              title="未通过原因"
              open={isModalOpen}
              onOk={handleOk}
              onCancel={handleCancel}
              okText="确定"
              cancelText="取消"
            >
              <TextArea
                value={textAreaValue}
                maxLength={100}
                onChange={handleTextAreaChange}
                placeholder="请输入审核未通过的原因"
                style={{ height: 120, resize: "none" }}
              />
            </Modal>
          </>
        );
      },
    },
    {
      title: "需要申请",
      dataIndex: "subjectIsApply",
      key: "subjectIsApply",
      align: "center",
      width: "150px",
      render: (_: any, record: any) => {
        return (
          <Radio.Group
            value={record.subjectIsApply}
            options={COURSE_APPLY}
            onChange={(e) => handleChangeApply(e, record.id)}
            style={{ width: "100%" }}
          ></Radio.Group>
        );
      },
    },
    {
      title: "未通过原因",
      dataIndex: "cause",
      key: "cause",
      width: "150px",
      render: (_: any, record: any) => {
        return (
          <>
            {record.cause === "无" ? (
              <span>无</span>
            ) : (
              <Popover content={<p>{record.cause}</p>} title="原因">
                <span style={{ cursor: "pointer" }}>{record.cause}</span>
              </Popover>
            )}
          </>
        );
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      key: "option",
      align: "center",
      width: "120px",
      render: (_: any, record: any) => {
        return (
          <Space>
            <Popconfirm
              title="删除课题"
              description="你确定要删除本课题吗"
              onConfirm={() => removeCourse(record.id)}
            >
              <a>删除</a>
            </Popconfirm>
            <a onClick={() => editeVedio(record.id)}>编辑</a>
          </Space>
        );
      },
    },
  ];
  const [sId, setSId] = useState(0); //课题id
  const [courseId, setCourseId] = useState(0);
  const [open, setOpen] = useState(false);
  const [courseOpen, setCourseOpen] = useState(false);
  const [id, setId] = useState(0); //课程id
  const [imgUrl, setImgUrl] = useState("");
  const [videoUrl, setVideoUrl] = useState<string>("");
  const [form] = useForm();
  const [pageOptions, setPageOptions] = useState({ current: 1, pageSize: 10 });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [textAreaValue, setTextAreaValue] = useState("");
  const [courseName, setCourseName] = useState("");
  const [expandDataSource, setExpandDataSource] = useState([]);
  //  根据课程名查询
  const onCourseNameSearch: SearchProps["onSearch"] = (value, _e, info) => {
    getVideos(1, 10, value);
    console.log(value, _e, info);
  };
  //根据状态查询
  const handleSearchByStatus = (value: number) => {
    console.log(value);
    getVideos(1, 10, undefined, value);
  };
  //控制课程状态
  const handleChangeStatus = async (value: number, id: number) => {
    const res = await updateCourse({ id, subjectId: sId, videoStatus: value });
    if (res.data.code === 200) {
      getVideos(1, 10);
      getCourses(sId);
      message.success(res.data.msg);
    } else {
      message.error(res.data.msg);
    }
  };

  //控制申请
  const handleChangeApply = async (e: any, id: number) => {
    const res = await updateVideo({ subjectIsApply: e.target.value, id });
    if (res.data.code === 200) {
      getVideos(1, 10);
      message.success(res.data.msg);
    } else {
      message.error(res.data.msg);
    }
  };
  const onClose = () => {
    setId(0);
    setImgUrl("");
    form.resetFields();
    setOpen(false);
  };
  //课题表单
  const onFinish = async (value: any) => {
    if (id) {
      const res = await updateVideo({
        ...value,
        id,
        subjectHead: imgUrl[0],
        userId: parseInt(localStorage.getItem("userId") as string),
      });
      if (res.data.code === 200) {
        message.success(res.data.msg);
        getVideos(1, 10);
        setId(0);
        setImgUrl("");
        form.resetFields();
      }
    } else {
      const res = await addVideo({
        ...value,
        id,
        subjectHead: imgUrl[0],
        userId: parseInt(localStorage.getItem("userId") as string),
      });
      if (res.data.code === 200) {
        getVideos(1, 10);
        setId(0);
        setImgUrl("");
        form.resetFields();
        setOpen(false);
        message.success(res.data.msg);
      }
    }
  };

  const onFinishFailed = (value: any) => {
    console.log(value, "sucess");
  };

  //删除课题
  const removeCourse = async (id: number) => {
    const res = await delVideo({ subjectIds: id });
    if (res.data.code === 200) {
      message.success(res.data.msg);
      getVideos(1, 10);
    } else {
      message.error(res.data.msg);
    }
  };
  // 编辑课题
  const editeVedio = (id: number) => {
    setSId(id);
    setOpen(true);
  };
  // 分页
  const handlePageChange = (current: number, pageSize: number) => {
    setPageOptions({ current, pageSize });
    getVideos(current, pageSize);
  };
  const paginationOptions = {
    current: pageOptions.current,
    pageSize: pageOptions.pageSize,
    showQuickJumper: true,
    total,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: handlePageChange,
  };
  //课题审核未通过对话框
  const handleOk = async () => {
    const res = await auditSubject({
      subjectIds: [sId],
      cause: textAreaValue,
      notPassId: 2,
    });
    debugger;
    if (res.data.code === 200) {
      getVideos(1, 10);
      message.success(res.data.msg);
    }

    setTextAreaValue("");
    setIsModalOpen(false);
  };
  //改变课题状态
  const handleChangeCourseStatus = async (value: number, id: number) => {
    if (value === 1) {
      const res = await auditSubject({
        subjectIds: [id],
        passId: 1,
        cause: "无",
      });
      if (res.data.code === 200) {
        getVideos(1, 10);
        message.success(res.data.msg);
      }
    }
    if (value === 2) {
      setSId(id);
      setIsModalOpen(true);
    }
  };
  const handleCancel = () => {
    setTextAreaValue("");
    setIsModalOpen(false);
  };
  const handleTextAreaChange = (e: any) => {
    setTextAreaValue(e.target.value);
  };

  const expandColumns = [
    { title: "名称", dataIndex: "videoName", key: "videoName" },
    {
      title: "状态",
      key: "videoStatus",
      render: (_: any, record: any) => (
        <Dropdown
          menu={{
            items: [
              {
                label: (
                  <Badge
                    status={getCourseObj(0)?.status as TStatus}
                    text={getCourseObj(0)?.text}
                  />
                ),
                key: 0,
                onClick: () => handleChangeStatus(0, record.id),
              },

              {
                label: (
                  <Badge
                    status={getCourseObj(1)?.status as TStatus}
                    text={getCourseObj(1)?.text}
                  />
                ),
                key: 1,
                onClick: () => handleChangeStatus(1, record.id),
              },
              {
                label: (
                  <Badge
                    status={getCourseObj(2)?.status as TStatus}
                    text={getCourseObj(2)?.text}
                  />
                ),
                key: 2,
                onClick: () => handleChangeStatus(2, record.id),
              },
              {
                label: (
                  <Badge
                    status={getCourseObj(3)?.status as TStatus}
                    text={getCourseObj(3)?.text}
                  />
                ),
                key: 3,
                onClick: () => handleChangeStatus(3, record.id),
              },
            ],
          }}
        >
          <Badge
            status={getCourseObj(record.videoStatus)?.status as TStatus}
            text={getCourseObj(record.videoStatus)?.text}
          />
        </Dropdown>
      ),
    },
    {
      title: "链接",
      dataIndex: "videoLink",
      key: "videoLink",
      render: (_: any, record: any) => (
        <a href={`${SEVER_URL}${record.videoLink}`}>点击观看视频</a>
      ),
    },
    {
      title: "操作",
      key: "operation",
      render: (_: any, record: any) => (
        <Space size="middle">
          <a onClick={() => editeCourse(record.id)}>编辑</a>
          <Popconfirm
            title="删除课程内容"
            description="你确定要删除本条课程内容吗？"
            onConfirm={() => delTheCourse(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  //
  //编辑课程
  const editeCourse = (id: number) => {
    setCourseOpen(true);
    setCourseId(id);
  };
  //删除课程
  const delTheCourse = async (id: number) => {
    console.log(id);
    const res = await delCourse([id]);
    if (res.data.code === 200) {
      message.success(res.data.msg);
      getCourses(sId);
    }
  };

  const expandedRowRender = () => (
    <Table
      columns={expandColumns}
      dataSource={expandDataSource}
      pagination={false}
    />
  );
  //课程对话框
  const courseMadolCancel = () => {
    setCourseName("");
    setVideoUrl("");
    setCourseOpen(false);
  };
  // 编辑课程
  const courseModalOk = async () => {
    const res = await updateCourse({
      id: courseId,
      subjectId: sId,
      videoLink: videoUrl,
      videoName: courseName,
      subjectStatus: 0,
    });
    if (res.data.code === 200) {
      getCourses(sId);
      courseMadolCancel();
      message.success(res.data.msg);
    }
  };
  const getCourses = async (subjectId: number) => {
    const res = await getCourse({ pageNum: 1, pageSize: 100, subjectId });
    setExpandDataSource(res.data.data.records);
  };
  //点击展开按钮时触发
  const onExpand = async (expanded: any, record: any) => {
    getCourses(record.id);
    setSId(record.id);
  };

  return (
    <div className={style["Container"]}>
      <div className={style["header"]}>
        <Space>
          <Search
            placeholder="课程搜索"
            onSearch={onCourseNameSearch}
            style={{ width: 200 }}
            maxLength={32}
          />

          <Button onClick={() => setOpen(true)}>添加视频</Button>
          <Select
            options={COURSE_STATUS}
            onChange={handleSearchByStatus}
            placeholder={"请选择状态"}
            style={{ width: 120 }}
          ></Select>
        </Space>
      </div>
      <div className={style["content"]}>
        <TableCom
          dataSource={courses}
          columns={COURSE_CLOUMNS}
          className={style["table"]}
          paginationOptions={paginationOptions}
          expandable={{
            expandedRowRender,
            defaultExpandedRowKeys: ["0"],
            onExpand,
          }}
        />

        <Drawer
          title={id ? "编辑课程" : "添加课程"}
          onClose={onClose}
          open={open}
          size="large"
          width={460}
          style={{ padding: 10, maxWidth: 800 }}
        >
          <CourseForm
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            id={id}
            imgUrl={imgUrl}
            setImgUrl={setImgUrl}
            form={form}
          ></CourseForm>
        </Drawer>
        <CourseModal
          open={courseOpen}
          videoUrl={videoUrl}
          setVedioUrl={setVideoUrl}
          courseName={courseName}
          setCourseName={setCourseName}
          onCancel={courseMadolCancel}
          onOk={courseModalOk}
          courseId={courseId}
        ></CourseModal>
      </div>
    </div>
  );
}
